<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="200px">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="form.name" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="参与奖数量" prop="joinGoodId">
          <el-select v-model="form.joinGoodId" filterable placeholder="请选择材料">
            <el-option
              v-for="item in goodlistData"
              :key="item.goodId"
              :label="item.goodName"
              :value="item.goodId"
            />
          </el-select>
          </el-form-item>
          <el-form-item label="参与奖数量" prop="joinGoodNum">
            <el-input v-model="form.joinGoodNum" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="服务器选择" prop="serverId">
            <el-select v-model="form.serverId" placeholder="请选择服务器">
              <el-option
                v-for="item in serverlistData"
                :key="item.id"
                :label="item.name"
                :value="item.id + ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="国王排名活动描述" prop="activateDesc">
            <el-input type="textarea" v-model="form.activateDesc"></el-input>
          </el-form-item>
          <el-form-item label="活动截止时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="12:00:00"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="活动名称" />
        <el-table-column prop="taskId" label="活动流水号" />
        <el-table-column prop="runStatus" label="活动状态" />
        <el-table-column prop="activateDesc" label="活动标题">
          <template #default="{ row }">
            <span
              @click="showFullDescription(row.activateDesc)"
              style="color: #409EFF; cursor: pointer; "
            >
              标题详情
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="joinGoodId" label="参与奖物品名">
          <template #default="{ row }">
            {{ row.joinGoodId | getgoodName(goodlistData) }}
          </template>
        </el-table-column>
        <el-table-column prop="joinGoodNum" label="参与奖数量" />
        <el-table-column prop="serverId" label="服务器信息">
          <template #default="{ row }">
            {{ row.serverId | getserviceName(serverlistData) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="活动截止时间" />
                <el-table-column v-if="checkPer(['admin','pokerActivateInfo:edit','pokerActivateInfo:del'])" label="阵容配置" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              @click="getTeam(scope.row)"
            >阵容配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','pokerActivateInfo:edit','pokerActivateInfo:del'])" label="阵容排名奖" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              @click="getAward(scope.row)"
            >排名奖励配置
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','pokerActivateInfo:edit','pokerActivateInfo:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.runStatus===0"
              class="filter-item"
              size="mini"
              type="primary"
              @click="start(scope.row)"
            >开启活动
            </el-button>
            <el-button
              v-if="scope.row.runStatus===1"
              class="filter-item"
              size="mini"
              type="primary"
              @click="getJiesuanView(scope.row)"
            >结算
            </el-button>
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog
      title="奖励配置"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <template>
        <el-table
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            prop="rank"
            label="名次"
            width="50"
          />
          <el-table-column
            prop="awardContent"
            label="奖励内容"
          >
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.awardItems" :key="index">
                <el-tag type="info"> {{ item.name }} * {{ item.num }}</el-tag>
              </span>
            </template>>
          </el-table-column>
          <el-table-column label="删除" width="80px">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="deletAwardConfig(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="awardAdd = true">新增奖励</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增奖励"
      :visible.sync="awardAdd"
      width="20%"
      :before-close="handleClose"
    >
      <template>
        排名： <el-input v-model="rank" style="width: 200px;" /><br>
        <div v-for="(ele, index) in awardContent" :key="index">
          材料： <el-select v-model="ele.goodId" filterable placeholder="请选择材料">
            <el-option
              v-for="item in goodlistData"
              :key="item.goodId"
              :label="item.goodName"
              :value="item.goodId"
            />
          </el-select><br>
          数量：<el-input v-model="ele.num" style="width: 200px;" />
        </div>
        <el-button
          @click="awardContent.push({
            goodId: '',
            num: '',
            name:''
          })"
        >新增</el-button>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="awardAdd = false">取 消</el-button>
        <el-button type="primary" @click="doAddAward">确 定</el-button>
      </span>
    </el-dialog>


  <el-dialog
      title="阵容配置"
      :visible.sync="teamVisible"
      width="30%"
      :before-close="handleClose"
    >
      <template>
        <el-table
          :data="teamDate"
          style="width: 100%"
        >
          <el-table-column
            prop="groupName"
            label="阵容名称"
          />
          <el-table-column label="删除" width="80px">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="deleteTeamConfig(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="teamAdd = true">新增阵容</el-button>
        <el-button @click="teamVisible = false">取 消</el-button>
      </span>
    </el-dialog>

<el-dialog
    title="结算页面"
    :visible.sync="jiesuanVisible"
    width="30%"
    :before-close="handleClose"
  >
    <!-- 胜利阵容 - 单选 -->
    <div class="selection-group">
      <h4>选择胜利阵容：</h4>
      <el-radio-group v-model="selectedRankGroup">
        <div
          v-for="team in teamDate"
          :key="team.id"
          class="radio-item"
        >
          <el-radio :label="team.id">{{ team.groupName }}</el-radio>
        </div>
      </el-radio-group>
    </div>

    <!-- 参与奖阵容 - 复选 -->
    <div class="selection-group">
      <h4>选择参与奖阵容：</h4>
      <el-checkbox-group v-model="selectedJoinGroups">
        <div
          v-for="team in teamDate"
          :key="team.id"
          class="checkbox-item"
        >
          <el-checkbox :label="team.id">{{ team.groupName }}</el-checkbox>
        </div>
      </el-checkbox-group>
    </div>

    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleJieSuan()">结算</el-button>
      <el-button @click="jiesuanVisible = false">取 消</el-button>
    </span>
  </el-dialog>

    <el-dialog
      title="新增阵容"
      :visible.sync="teamAdd"
      width="20%"
      :before-close="handleClose"
    >
      <template>
        阵容名称： <el-input v-model="teamName" style="width: 200px;" /><br>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="teamAdd = false">取 消</el-button>
        <el-button type="primary" @click="doAddTeam">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import crudPokerActivateInfo from '@/api/system/pokerActivateInfo'
import { startActivate, randmoCard, serverList, endActivate ,endKingActivate} from '@/api/system/pokerActivateInfo'
import { goodList } from '@/api/system/pokerGoodInfo'

import { list, add, del, teamList,addTeam ,delTeam} from '@/api/system/pokerActivateAwardInfo'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, name: null, pubPoker1: null, pubPoker2: null, changePokerBaseNum: null, changePokerAddNum: null, activeFreeChage: null, activeMaxChage: null, fontPrizeNum: null, fontPrizeNumGoodid: null, fontPrizeThirdGoodid: null, specialGoodid: null, endTime: null, serverId: null,activateType :1 }
export default {
  name: 'PokerActivateInfo',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'activate', url: 'api/pokerActivateInfo', idField: 'id', sort: 'id,desc', crudMethod: { ...crudPokerActivateInfo }})
  },
  data() {
    return {
      cyjVisible:false,
      teamVisible:false,
      teamAdd:false,
      jiesuanVisible:false,
      selectedRowId: null,
      selectedGroupName:null,

      dialogVisible: false,
      awardAdd: false,
      rank: undefined,
      teamName:undefined,
      serverlistData: [],
      goodlistData: [],
      activateId: '',
      activateAwardId: undefined,
      awardContent: [{
        goodId: '',
        num: '',
        name: ''
      }],

      permission: {
        add: ['admin', 'pokerActivateInfo:add'],
        edit: ['admin', 'pokerActivateInfo:edit'],
        del: ['admin', 'pokerActivateInfo:del']
      },
      rules: {
        name: [
          { required: true, message: '活动名称不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '活动截止时间不能为空', trigger: 'blur' }
        ]
      },
      tableData: [],
      teamDate:[],
      selectedRankGroup: null,
      selectedJoinGroups: []
    }
  },

  filters: {
    getserviceName(value, listData) {
      const item = listData.find(ele => {
        return ele.id === Number(value)
      })
      return item ? item.name : ''
    },
    getgoodName(value, listData) {
      const item = listData.find(ele => {
        return ele.goodId === String(value)
      })
      return item ? item.goodName : ''
    },
  },

  created() {
    this.crud.query.activateType = 1;
    this.crud.refresh();
    this.getserverList()
    this.getgoodList()
  },
  methods: {
    showFullDescription(desc) {
    this.$alert(desc, '活动描述', {
      confirmButtonText: '确定',
      callback: () => {}
    });
  },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // materialsAdd() {
    //   console.log(this.awardContent, 'awardContent')
    // },
    handleClose() {
      this.dialogVisible = false
      this.activateId = ''
    },
    getAward(row) {
      this.dialogVisible = true
      console.log(row)
      const param = {
        activateId: row.id
      }
      this.activateAwardId = row.id
      this.activateId = row.id || ''
      list(param).then((res) => {
        this.tableData = res.awardList.map(item => ({
          ...item,
          awardItems: JSON.parse(item.awardContent)
        }))

        console.log(this.tableData)
      })
    },
    getTeam(row) {
      this.teamVisible = true
      const param = {
        activateId: row.id
      }
      this.activateAwardId = row.id
      this.activateId = row.id || ''
      teamList(param).then((res) => {
        this.teamDate = res;
        console.log(res,"this.teamdate");
      })
    },

    getJiesuanView(row) {
      this.jiesuanVisible = true
      const param = {
        activateId: row.id
      }
      this.activateAwardId = row.id
      this.activateId = row.id || ''
      teamList(param).then((res) => {
        this.teamDate = res;
        console.log(res,"this.teamdate");
      })
    },

    deletAwardConfig(row) {
      const param = {
        id: row.id
      }
      del(param).then((res) => {
        this.$message.success('删除成功')
        this.refreshAwardList()
      })
    },

    deleteTeamConfig(row) {
      const param = {
        id: row.id
      }
      delTeam(param).then((res) => {
        this.$message.success('删除成功')
        this.refreshTeamList()
      })
    },

    doAddAward() {
      // 检查是否已存在相同名次
      const isRankExist = this.tableData.some(item => item.rank == this.rank);

      if (isRankExist) {
        this.$message.warning('已经存在该排名，请核验');
        return;
      }

      // 填充物品名称
      this.awardContent.forEach(iteminsert => {
        if (!iteminsert.goodId) return;

        const goodItem = this.goodlistData.find(good => good.goodId === iteminsert.goodId);
        if (goodItem) {
          iteminsert.name = goodItem.goodName;
        }
      });

      // 构造参数
      const param = {
        activateId: this.activateAwardId,
        awardContent: this.awardContent,
        rank: this.rank
      };

      // 调用接口添加
      add(param).then(() => {
        this.$message.success('新增成功');
        this.refreshAwardList(); // 刷新奖励列表
        this.awardAdd = false;   // 关闭弹窗
      }).catch(() => {
        this.$message.error('新增失败');
      });
      this.rank=undefined;
      this.awardContent=[{
        goodId: '',
        num: '',
        name: ''
      }]
    },

    doAddTeam() {
      // 构造参数
      const param = {
        groupName: this.teamName,
        activateId: this.activateAwardId

      };

      // 调用接口添加
      addTeam(param).then(() => {
        this.$message.success('新增成功');
        this.refreshTeamList(); // 刷新奖励列表
        this.teamAdd = false;   // 关闭弹窗
      }).catch(() => {
        this.$message.error('新增失败');
      });
      this.teamName=undefined;
    },

    
    refreshAwardList() {
      const params = {
        activateId: this.activateAwardId
      }
      list(params).then((res) => {
        console.log(res,"res");
        this.tableData = res.awardList.map(item => ({
          ...item,
          awardItems: JSON.parse(item.awardContent)
        }))
      })
    },

    refreshTeamList() {
      const params = {
        activateId: this.activateAwardId
      }
      teamList(params).then((res) => {
        this.teamDate = res
      })
    },

    start(row) {
      const param = {
        id: row.id
      }
      startActivate(param).then((res) => {
        this.$message.success('活动开启成功')
        location.reload()
  
      })
    },

    end(row) {
      const param = {
        id: row.id
      }
      endActivate(param).then((res) => {
        this.$message.success('结算完成')
        location.reload()
      })
    },
    randmoCardApi(poker) {
      randmoCard().then((res) => {
        if (poker == 1) {
          this.$message.success(res)
          this.form.pubPoker1 = res
        } else if (poker == 2) {
          this.$message.success(res)
          this.form.pubPoker2 = res
        }
      })
    },

    getserverList() {
      serverList().then((res) => {
        this.serverlistData = res
      })
    },

    getgoodList() {
      goodList().then((res) => {
        this.goodlistData = res
      })
    },

handleJieSuan() {
    const { selectedRankGroup, selectedJoinGroups, teamDate } = this;

    // 获取队伍名称用于显示（防止找不到的情况）
    const rankGroup = teamDate.find(t => t.id === selectedRankGroup);
    const rankGroupName = rankGroup ? rankGroup.groupName : '';

    const joinGroupNames = selectedJoinGroups
      .map(id => {
        const group = teamDate.find(t => t.id === id);
        return group ? group.groupName : '';
      })
      .filter(name => name); // 过滤掉空字符串

    // 校验逻辑
    if (!selectedRankGroup) {
      this.$message.warning('请选择胜利阵容');
      return;
    }

    if (joinGroupNames.length === 0) {
      this.$message.warning('请至少选择一个参与奖阵容');
      return;
    }

    // 显示确认信息
      const confirmText = `
        <div style="
          padding: 15px;
          background-color: #f9f9f9;
          border-radius: 6px;
          font-family: Arial, sans-serif;
          color: #333;
          text-align: left;
          max-width: 100%;
          line-height: 1.8;
        ">
          <strong style="font-size: 16px; color: #333;">请确认以下选择：</strong><br/><br/>
          
          <div style="margin-left: 10px;">
            <span style="font-weight: bold; color: #409EFF;">胜利阵容：</span>
            <span style="font-size: 14px;">${rankGroupName}</span>
          </div>
          
          <div style="margin-left: 10px; margin-top: 8px;">
            <span style="font-weight: bold; color: #409EFF;">参与奖阵容：</span>
            <span style="font-size: 14px;">${joinGroupNames.join('、')}</span>
          </div>
        </div>
      `;

    this.$confirm(confirmText, '确认提交', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    })
      .then(() => {
      const param = {
        activateId: this.activateId,
        rankGroupId:this.selectedRankGroup,
        joinGroupIds:this.selectedJoinGroups.join(',')
      }
      endKingActivate(param).then((res) => {
        this.$message.success('结算完成')
        location.reload()
      })
        this.jiesuanVisible = false; // 关闭弹窗
      })
      .catch(() => {
        this.$message.info('已取消提交');
      });
  }
  }
}
</script>

<style scoped>
::v-deep .el-table .selected-row > td {
  background-color: #e8f4ff !important; /* 柔和蓝底 */
  color: #1a73e8 !important;
  font-weight: bold;
}

::v-deep .el-table__row.selected-row {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

::v-deep .el-table th,
::v-deep .el-table .el-table__row {
  height: 50px;
}

::v-deep .el-table__body tr.hover-row:not(.selected-row) > td {
  background-color: #f8f8f8 !important;
}

::v-deep .group-name-text {
  font-size: 16px;        /* 放大字体 */
  font-weight: 600;       /* 加粗 */
  color: #333;            /* 深灰色，比默认黑色更柔和 */
  display: inline-block;
  line-height: 1.5;
}
</style>